//
//  OCRController.m
//  QuanNengSaoMiaoZhuShou
//
//  Created by 于博文 on 16/3/14.
//  Copyright © 2016年 于博文. All rights reserved.
//
#import "OCRController.h"
#import "ProgressView.h"
#import <CoreImage/CIFilter.h>
#import "URLHeader.h"
@interface OCRController ()<G8TesseractDelegate>

@property (nonatomic,strong)UIActivityIndicatorView *activityIndicator;
@property (nonatomic,strong)NSOperationQueue *operationQueue;
@property (nonatomic,strong)ProgressView *progressV;
@property (nonatomic,strong)UIView *shadeView;
@property (nonatomic,strong)UIButton *button;
///存储需要解析的图片
@property (nonatomic,strong)UIImage *recognizeImage;

@end

@implementation OCRController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    NSLog(@"%@",self.arrayForImage);
    UIImage *image = self.arrayForImage.lastObject;
//    CGRect rect = CGRectMake(0, 0, 1400,1500 );
//    self.OCRImageV.image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, rect) scale:1 orientation:UIImageOrientationRight];
    self.OCRImageV.image = self.arrayForImage.lastObject;
    [self.view addSubview:self.OCRImageV];
    self.operationQueue = [[NSOperationQueue alloc]init];
}

//自动
- (IBAction)autoAction:(id)sender {
   UIImage *image1 = [self sarpen:self.OCRImageV.image];
   UIImage *image2 = [image1 g8_blackAndWhite];
   self.OCRImageV.image = [self grayImage:image2];
}
//原图
- (IBAction)originalAction:(id)sender {
    self.OCRImageV.image = self.arrayForImage.lastObject;
}
//增亮
- (IBAction)lightAction:(id)sender {
    self.OCRImageV.image = [self light:self.OCRImageV.image];
}
//增强并锐化
- (IBAction)sarpenAction:(id)sender {
   self.OCRImageV.image = [self sarpen:self.OCRImageV.image];
    
}
//黑白
- (IBAction)blackAndWhite:(id)sender {
    self.OCRImageV.image = [self.OCRImageV.image g8_blackAndWhite];
}
//灰度
- (IBAction)garyAction:(id)sender {
    self.OCRImageV.image = [self grayImage:self.OCRImageV.image];
}

//灰度
-(UIImage *)grayImage:(UIImage *)source
{
    int width = source.size.width;
    int height = source.size.height;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGContextRef context = CGBitmapContextCreate (nil,
                                                  width,
                                                  height,
                                                  8,      // bits per component
                                                  0,
                                                  colorSpace,
                                                  kCGImageAlphaNone);
    CGColorSpaceRelease(colorSpace);
    if (context == NULL) {
        return nil;
    }
    CGContextDrawImage(context,
                       CGRectMake(0, 0, width, height), source.CGImage);
    UIImage *grayImage =  [UIImage imageWithCGImage:CGBitmapContextCreateImage(context) scale:1 orientation:UIImageOrientationRight];
    //UIImage *grayImage = [UIImage imageWithCGImage:];
    CGContextRelease(context);
    return grayImage;
}
//亮度
- (UIImage *)light:(UIImage *)image{
    
    //使用CGImage初始化CIImage对象
    CIImage *imageCI = [CIImage imageWithCGImage:image.CGImage];
    //创建一个滤镜对象
    CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];
    //利用键值对来设置滤镜的属性（后面的key在CIFilter中都可以找到，然后拿到这些key进行相应的赋值即可）
    [filter setValue:imageCI forKey:kCIInputImageKey];
    //设置图片的亮度
    [filter setValue:@1.7 forKey:kCIInputSaturationKey];
    //得到滤镜处理后的CIImage
    CIImage *imageOut = [filter outputImage];
    //初始化CIContext对象
    CIContext *context = [CIContext contextWithOptions:nil];
    //利用CIContext对象渲染后得到CGImage，最后将它转成UIImage
    CGImageRef outImage = [context createCGImage:imageOut fromRect:imageOut.extent];
    UIImage *outPutImage = [UIImage imageWithCGImage:outImage scale:1 orientation:UIImageOrientationRight];
    //释放CGImage对象，一定不要忘记自己释放
    CGImageRelease(outImage);
    return outPutImage;
}
//锐化
- (UIImage *)sarpen:(UIImage *)sarpenImage{
    UIImage *imageUI = sarpenImage;
    CIImage *imageCI = [CIImage imageWithCGImage:imageUI.CGImage];
    CIFilter *filter = [CIFilter filterWithName:@"CIUnsharpMask"
                                  keysAndValues:kCIInputImageKey, imageCI,
                        @"inputRadius", [NSNumber numberWithFloat:2.5],
                        @"inputIntensity", [NSNumber numberWithFloat:0.5],
                        nil];
    [filter setDefaults];
    //CIFilter *filter = [CIFilter filterWithName:@"CISepiaTone" keysAndValues: kCIInputImageKey, beginImage, @"inputIntensity", @0.8, nil];
    //获取绘制上下文
    CIContext *context = [CIContext contextWithOptions:nil];
    //渲染并输出CIImage
    CIImage *outputImage = [filter outputImage];
    //创建CGImage句柄
    CGImageRef cgImage = [context createCGImage:outputImage fromRect:[outputImage extent]];
    //获取图片
    // UIImage *image = [UIImage imageWithCGImage:cgImage];
    UIImage * image =  [UIImage imageWithCGImage:cgImage scale:1 orientation:UIImageOrientationRight];
    //释放CGImage句柄
    CGImageRelease(cgImage);
    
    return  image;

}

- (IBAction)leftTurnAction:(id)sender {
    
    self.OCRImageV.transform = CGAffineTransformMakeRotation(M_1_PI/2);
    
}
- (IBAction)rightTurnAction:(id)sender {
    
}







//解析按钮
- (IBAction)recognizeAction:(UIButton *)sender{
    [self recognizeImageWithTesseract:self.OCRImageV.image];
}
//解析方法
- (void)recognizeImageWithTesseract:(UIImage *)image{
    
    UIImage *sarpen = [self sarpen:image];
    UIImage *gray = [self grayImage:sarpen];
    UIImage *showImage = [gray g8_blackAndWhite];
    //设置菊花
    [self setProgressView];
    //这里设置要展示出来的图片
    self.OCRImageV.image = showImage;
    //1,设置语言
    G8RecognitionOperation *operation = [[G8RecognitionOperation alloc]initWithLanguage:@"chi_sim"];
    //2,设置解析模式
    operation.tesseract.engineMode = G8OCREngineModeTesseractOnly;
    operation.tesseract.pageSegmentationMode = G8PageSegmentationModeAutoOnly;
    //3,设置代理
    operation.delegate = self;
    //4,设置解析源
    operation.tesseract.image = showImage;
    //5,完成识别
    operation.recognitionCompleteBlock = ^(G8Tesseract *resseract){
        //获取识别出来的文字
        NSString *recingnizedText = resseract.recognizedText;
        NSLog(@"解析结果: %@",recingnizedText);
        //此处为主线程
        //此处移除菊花
        self.shadeView.hidden = YES;
    };
    [self.operationQueue addOperation:operation];
}
//观察进度的代理
- (void)progressImageRecognitionForTesseract:(G8Tesseract *)tesseract{
    //注意: 此处为子线程
    NSLog(@"已经解析 : %lu",tesseract.progress);
    //CGFloat temp = (CGFloat)(tesseract.progress-30)/56.6;
    //NSLog(@"%f",(CGFloat)(tesseract.progress));
    dispatch_async(dispatch_get_main_queue(), ^{
        CGFloat value =(CGFloat)(tesseract.progress-30)/56.6;
        
        if (value > 1) {
            value = 0.99;
            self.progressV.progressValue = value;
        }else{
            
            self.progressV.progressValue = value;
        }
    });
}
- (void)setProgressView{
    ProgressView *circleProgress2 = [ProgressView viewWithFrame:CGRectMake(self.view.center.x-15, self.view.center.y-15, 30, 30)                                                 circlesSize:CGRectMake(34, 2, 30, 30)];
    circleProgress2.layer.cornerRadius = 10;
    //阴影
    circleProgress2.backgroundColor = [UIColor clearColor];
    circleProgress2.backCircle.shadowColor = [UIColor grayColor].CGColor;
    circleProgress2.backCircle.shadowRadius = 3;
    circleProgress2.backCircle.shadowOffset = CGSizeMake(0, 0);
    circleProgress2.backCircle.shadowOpacity = 1;
    circleProgress2.backCircle.fillColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:0.8].CGColor;
    circleProgress2.backCircle.strokeColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1].CGColor;
    circleProgress2.foreCircle.lineCap = @"butt";
    circleProgress2.foreCircle.strokeColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:1].CGColor;;
    circleProgress2.progressValue = 0;
    [self.shadeView addSubview:circleProgress2];
    self.progressV = circleProgress2;
}
//返回
- (IBAction)backAction:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 懒加载
- (NSMutableArray *)arrayForImage{
    if (!_arrayForImage) {
        _arrayForImage = [NSMutableArray array];
    }
    return _arrayForImage;
}
- (UIView *)shadeView{
    if (!_shadeView) {
        _shadeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        _shadeView.alpha = 0.5;
        _shadeView.backgroundColor = [UIColor blackColor];
        [self.view addSubview:_shadeView];
    }
    return _shadeView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
